<template>
    <div class="app-container">
        <levelbar></levelbar>
        <TableLayout form-title="">
            <div slot="form-title" class="table-title"></div>
            <el-form :model="query" ref="query" :rules="rules" slot="form" label-width="76px" label-position="right">
                <el-row :gutter="41">
                    <el-col :span="8" v-if="schoolType == '0'">
                        <el-form-item label="年级" prop="grade">
                            <el-select v-if="roleType == '2' || roleType == '1'" v-model="query.grade" :clearable="roleType == '2' || roleType == '1'" placeholder="请选择" style="width:100%;" @change="getClassListFu( query.grade )">
                                <el-option v-for="item in gradeList" :key="item.pId" :label="item.sName" :value="item.pId">
                                </el-option>
                            </el-select>
                            <el-select v-if="roleType == '5'" v-model="query.grade" :clearable='true' placeholder="请选择" style="width:100%;" @change="getClassListFu1( query.grade )">
                                <el-option v-for="item in gradeList" :key="item.gradeId" :label="item.gradeName" :value="item.gradeId">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="班级名称" prop="classId">
                            <el-select  v-if="roleType == '2' || roleType == '1'" v-model="query.classId" :clearable="roleType == '2' || roleType == '1'" placeholder="请选择" style="width:100%;">
                                <el-option v-for="item in classList" :key="item.classId" :label="item.classNickName" :value="item.classId">
                                </el-option>
                            </el-select>
                            <el-select v-if="roleType == '5'" v-model="query.classId" :clearable='true' placeholder="请选择" style="width:100%;">
                                <el-option v-for="item in classList" :key="item.classId" :label="item.className" :value="item.classId">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="e学云ID号" prop="eID">
                            <el-input v-model="query.eID" placeholder="请输入" style="width:100%" :maxlength="10"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" v-if="schoolType == '1'">
                        <el-form-item label="姓名" prop="studentName">
                            <el-input v-model="query.studentName" placeholder="请输入" style="width:100%"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="41">
                    <el-col :span="8" v-if="schoolType == '0'">
                        <el-form-item label="姓名" prop="studentName">
                            <el-input v-model="query.studentName" placeholder="请输入" style="width:100%"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="家长手机" prop="parentPhone">
                            <el-input v-model="query.parentPhone" placeholder="请输入" style="width:100%" :maxlength="11"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <div class="top-line">
                    <el-button type="primary" class="top-btn" @click="onSubmit('query')">查询</el-button>
                </div>
            </el-form>
            <div class="table-title" slot="table-title">
                <div class="btnPosition">
                    <el-button @click="addStudent()">新增</el-button>
                    <el-button @click="batchDelete()">批量删除</el-button>
                </div>
            </div>
            <el-table :data="tableData" border v-loading="loading" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" align="center" width="55"></el-table-column>
    
                <!-- <el-table-column label="学籍号" align="center">
                    <template scope="scope">
                        <span>{{scope.row.schoolrollCode | isNull}}</span>
                    </template>
                </el-table-column> -->
    
                <el-table-column label="e学云ID号" align="center">
                    <template scope="scope">
                        <span>{{scope.row.exueCode | isNull}}</span>
                    </template>
                </el-table-column>
    
                <el-table-column label="姓名" align="center">
                    <template scope="scope">
                        <span>{{scope.row.studentName | isNull}}</span>
                    </template>
                </el-table-column>
    
                <el-table-column label="性别" align="center">
                    <template scope="scope">
                        <span>{{scope.row.studentSex | isNull}}</span>
                    </template>
                </el-table-column>
    
                <el-table-column label="关联家长数" align="center">
                    <template scope="scope">
                        <span>{{!scope.row.relevanceParentNum?'0':scope.row.relevanceParentNum}}</span>
                    </template>
                </el-table-column>
    
                <el-table-column label="创建时间" width="170" align="center">
                    <template scope="scope">
                        <span>{{ scope.row.createTime | parseTime }}</span>
                    </template>
                </el-table-column>
    
                <el-table-column label="最后登陆时间" width="170" align="center">
                    <template scope="scope">
                        <span>{{ scope.row.lastLoginTime | parseTime  }}</span>
                    </template>
                </el-table-column>
                <!-- by cuihd 20180703 晓芳要求先掩藏 -->
                <!-- <el-table-column label="初始化密码" align="center">
                    <template scope="scope">
                        <el-button type="text" class="btn-success" @click="initPassword(scope.row)">初始化</el-button>
                    </template>
                </el-table-column> -->
    
                <el-table-column label="操作" width="240px">
                    <template scope="scope">
                        <el-button type="text" class="btn-success" @click="classInfor(scope.row)">班级信息</el-button>
                        <el-button type="text" class="btn-success" @click="studentInfor(scope.row)">学生信息</el-button>
                        <el-button type="text" class="btn-success" @click="deleteList(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination-container">
                <el-pagination layout="total, sizes, prev, pager, next, jumper" :total="pageQuery.total" :current-page.sync="pageQuery.currentpage" :page-sizes="config.pageSizes" :page-size="config.pageSize" @size-change="handleSizeChange" @current-change="handleCurrentChange">
                </el-pagination>
            </div>
        </TableLayout>
        <!-- created by cuihd at 20180712 优化批量删除 添加进度条-->
        <el-dialog :title="dialogTitle" size="tiny" :visible.sync="dialogTimeout">
            <el-progress v-if="progress == '100'" :percentage="progress" status="success"></el-progress>
            <el-progress v-else :percentage="progress"></el-progress>
        </el-dialog>
    </div>
</template>

<script>
    import Levelbar from '../layout/Levelbar';
    import TableLayout from 'components/TableLayout';
    import { getUserInfoDetail, getGradeInfoByUserIdAndSchoolId, getClassInfoList, getLoginRoleInfo,getStudentList, getGradeList, getClassList, initializePassword, deleteBatchStudentInfo, deleteBatchStudentInfoProgress, querySchoolByName, getGrade, getClass } from 'api/studentMange';
    import { mapGetters, mapState, mapActions } from 'vuex';
    import validate from '@/utils/validate';

    export default {
        name: 'studentManage',
        components: { Levelbar, TableLayout},
        data() {
            return { 
                loading: true,  
                roleState: '',
                gradeList: [],
                classList: [],
                tableData: [],
                pageQuery: {
                    currentpage: 1,
                    total: 0
                },
                query: {
                    schoolId: '',
                    grade: '',
                    classId: '',
                    eID: '',
                    studentName: '',
                    parentPhone: ''
                },
                multipleSelection: [],
                userId: '',
                rules: {
                    eID: [...validate.exueCode()],
                    parentPhone: [...validate.phone()]
                },
                /**
                 * created by cuihd at 20180709
                 * 优化批量删除学生
                 * 添加相关变量
                 */
                dialogTitle: '正在批量删除学生...',
                dialogTimeout: false,
                progress: 0
            }
        },
        created() {
            this.getUserInfoDetailFu();
        },
        watch: {// 局部刷新列表
            cacheUpdated(val) {
                val && this.queryData();
            }
        },
        computed: {
            ...mapGetters([
                'uid',
                'schoolId',
                'schoolName',
                'schoolType',
                'roleType'
            ]),
            ...mapState({
                config: state => state.config.table,
                cacheUpdated: state => state.app.cacheUpdated // 局部刷新列表
            })
        },
        methods: {
            ...mapActions(['ChangePageSize']),
            handleSizeChange(val) {
                this.pageQuery.currentpage = 1;
                this.ChangePageSize(val);
                this.queryData();
            },
            handleCurrentChange(val) {
                this.pageQuery.currentpage = val;
                this.queryData();
            },
            onSubmit(ruleForm) {
                this.$refs[ruleForm].validate((valid)=>{
                    if(valid){
                        this.pageQuery.currentpage = 1;
                        this.queryData();
                    }
                })
            },
            // tabClick(){
            //     this.$refs.myTable  
            // },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            getUserInfoDetailFu() {
                getUserInfoDetail().then( res => {
                    if (res.data.status == 200) {
                        this.roleState = res.data.content[0].userType;

                        // 2代表学校管理员  5代表班主任
                        if (this.roleType == '5' ) { // 5 班主任 6 // 学校管理员
                            this.userId = res.data.content[0].userId;
                            this.getGradeListFu1(this.schoolId);
                            this.queryData();
                        } else {
                            this.getGradeListFu(this.schoolId);
                            this.queryData();
                        }
                    } else {
                        this.$message.error(res.data.errorMsg);
                    }
                })
            },
            getGradeListFu(schoolId) {
                this.gradeList = [];
                this.query.grade = '';
                
                if(this.schoolId) {
                    if(this.schoolType == '1') {
                        getClassList(null, this.schoolId).then( res => {
                            this.classList = res.data.content;
                        })
                    } else {
                        getGradeList(schoolId).then( res => {
                            this.gradeList = res.data.content;
                        })
                    }
                }
            },
            getClassListFu(gradeId) {
                this.classList = [];
                this.query.classId = ''; 
               
                if(this.query.grade) {
                    getClassList(gradeId, this.schoolId).then( res => {
                        this.classList = res.data.content;
                    })
                }
            },
            getGradeListFu1(schoolId) {
                this.query.grade = '';
                if(this.schoolType == '1') {
                    this.query.classId = ''; 
                    // let userId = this.userId;
                    getClassInfoList(null, schoolId).then( res => {
                        this.classList = res.data.content;
                        // this.query.classId = res.data.content[0].classId;
                        this.queryData();
                    })
                } else {
                    // let userId = this.userId;
                    getGradeInfoByUserIdAndSchoolId(schoolId).then( res => {

                        this.gradeList = res.data.content;
                        for (var i = 0;i<this.gradeList.length;i++) {  
                            for (var j = i+1;j<this.gradeList.length;j++) {  
                                if(this.gradeList[i].gradeId == this.gradeList[j].gradeId){  
                                    this.gradeList.splice(j,1);  
                                    j--;  
                                }  
                            }  
                        }
                        if(res.data.content.length){
                            // this.query.grade = res.data.content[0].gradeId;
                        }
                        
                    })
                }
            },
            getClassListFu1(gradeId) {
                this.query.classId = ''; 
                this.classList = [];
                // let userId = this.userId;

                if(gradeId) {
                    getClassInfoList(gradeId, this.schoolId).then( res => {
                        this.classList = res.data.content;
                        // this.query.classId = res.data.content[0].classId;
                        // this.queryData();
                    })
                }
                
            },
            queryData() {
                let schoolId = this.schoolId; // 学校名称
                let grade = this.query.grade; // 年级
                let classId = this.query.classId; // 班级名称
                let eId = this.query.eID; // exueid
                let studentName = this.query.studentName; // 学生名称
                let parentPhone = this.query.parentPhone; 

                this.loading = true;
                getStudentList(
                    this.pageQuery.currentpage,
                    this.config.pageSize,
                    schoolId,
                    grade, // 年级
                    classId, // 班级
                    eId, // exueid
                    studentName, // 学生名称
                    parentPhone
                ).then(response => {
                    this.loading = false;
                    this.tableData = [];
                    if (response.data.status == 200) {
                        if (response.data.content) {
                            this.tableData = response.data.content.list;
                            this.pageQuery.total = response.data.content.pagination.total;
                        }
                    } else {
                        this.$message.error(response.data.errorMsg);
                    }
                    
                }).catch(() => {
                    this.loading = false;
                });
            },

           // 新增
            addStudent() {
                this.$router.push({ path: 'addStudentPage' });
            },

            // 学生信息
            studentInfor(obj) {
                this.$router.push({ path: `studentInforPage/${obj.studentId}`});
            },

            // 班级信息
            classInfor(obj) {
                this.$router.push({ path: `classInforPage/${obj.studentId}`});
            },

            // 初始化密码
            initPassword(obj) {
                this.$confirm('确定初始化用户【'+obj.studentName+'】的密码？', ' ', { 
                    closeOnClickModal: false,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: ' ' 
                }).then(() => {
                    this.loading = true;
                    initializePassword(obj.studentId).then(response => {
                        this.loading = false;
                        if (response.data.status == 200) {
                            this.$message.success('初始化密码成功，初始密码是111111');
                            this.queryData();
                        } else {
                            this.$message.error(response.data.errorMsg);
                        }
                    }).catch(() => {
                        this.loading = false;
                    });
                }).catch(() => {      
                    this.$message.info('已取消');   
                });
            },
            
            // 批量删除
            batchDelete() {              
                let studentIdList = [];
                if (this.multipleSelection.length == 0) {
                    this.$message('请选择需要删除的学生');
                    return;
                }
                for (let index=0; index<this.multipleSelection.length;index++) {
                    studentIdList.push(this.multipleSelection[index].studentId);
                }
                // this.deleteStudent(studentIdList.join(',')); 
                let studentId = studentIdList.join(',');
                this.$confirm('此操作将批量删除选中学生, 是否继续?', '', {
                    closeOnClickModal: false,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: ' ', // warning
                    title: '  '
                }).then(() => {
                    this.btnLoading = true;                  
                    this.loading = true;
                    deleteBatchStudentInfo(studentId, this.schoolId, this.schoolName).then(res => {
                        // this.$message.success(response.data.errorMsg);
                        // this.queryData();
                        // this.btnLoading = false;
                        /**
                         * created by cuihd at 20180710
                         * 优化批量删除教师
                         * 添加相关变量
                         */
                        if (res.data.content) {
                            let timeStamp = res.data.content.timeStamp;
                            let totalNum = res.data.content.totalNum;
                            this.dialogTitle = '正在批量删除学生...';
                            this.dialogTimeout = true;
                            this.progress = 0;
                            this.batchProgress(timeStamp, totalNum);
                        }
                        
                    }).catch(() => {
                        this.loading = false;
                        this.btnLoading = false;
                    })
                }).catch((e) => {
                    this.$message.info('已取消删除');     
                });
                
            },

            // created by cuihd at 20180712
            // 轮询接口获取未处理的数量
            batchProgress(timeStamp, totalNum) { // 递归轮询deleteBatchStudentInfoProgress接口
                totalNum = Number(totalNum); // 强转成number类型
                deleteBatchStudentInfoProgress(timeStamp).then(res => {
                    if(res.data.content >= 0 && res.data.content <= totalNum && res.data.content !== null){
                        if (res.data.content != 0) {
                            this.progress = parseInt((totalNum-Number(res.data.content))/totalNum*100);
                            setTimeout(() => {
                                this.batchProgress(timeStamp, totalNum);
                            }, 1000);
                        } else {
                            this.btnLoading = false;
                            this.dialogTitle = '批量删除学生成功';
                            this.progress = 100;
                            setTimeout(() => {                       
                                this.dialogTimeout = false;
                                this.queryData();
                            }, 500)
                        }
                    }else{
                        this.dialogTimeout = false;
                        this.$message({
                            message: '批量删除失败！',
                            type: 'error'
                        });
                        this.queryData();
                    }
                    
                }).catch(err => {
                    //console.log(err);
                })
            },

            // 删除
            deleteList(obj) {
                this.deleteStudent(obj.studentId+',');
            },

            // 删除功能
            deleteStudent(studentId) {
                this.$confirm('确定删除该学生？', '', {
                    closeOnClickModal: false,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: ' ', 
                    title: '  '
                }).then(() => {
                    this.loading = true;
                    deleteBatchStudentInfo(studentId, this.schoolId, this.schoolName).then(response => {
                        this.loading = false;
                        this.$message.success(response.data.errorMsg);
                        this.queryData();
                    }).catch(() => {
                        this.loading = false;
                    });
                }).catch((e) => {
                    this.$message.info('已取消删除');     
                });              
            }
        }

    }
</script>

<style lang="scss">
.el-message-box__message {
    p {
        font-size: 18px;
        color: #333;
        text-align: center;
    }
}

.el-message-box__btns {
    text-align: center;
}

.app-container {
    position: relative;
    padding: 20px 20px 10px;
    $bgcolor: #fff;
    .app-levelbar {
        height: 35px;
    }
}
</style>

